<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/12/7
 * Time: 9:20
 */

namespace app\storage\controller;

use app\storage\model\RoleModel;
use app\storage\model\StaffStorageModel;
use app\storage\model\StorageModel;
use app\storage\model\UserModel;
use app\storage\service\UserService;
use cmf\controller\AdminBaseController;
use think\Request;

class UserController extends AdminBaseController
{
    private $userModel;
    private $userService;

    public function __construct(UserService $userService, UserModel $userModel, Request $request = null)
    {
        parent::__construct($request);
        $this->userModel = $userModel;
        $this->userService = $userService;
    }

    public function index()
    {
        return $this->fetch('index');
    }

    public function add()
    {
        $role = RoleModel::all();
        $storage = StorageModel::all();
        $assign = [
            'role' => $role,
            'storage' => $storage
        ];
        $this->assign($assign);
        return $this->fetch('add');
    }

    public function edit()
    {
        $userId = input('id');
        $result = $this->userService->getUserInfo($userId);
        $assign['user'] = $result;
        $staffStorageModel = new StaffStorageModel();
        $storageModel = new StorageModel();
        $roleModel = new RoleModel();
        $assign['role'] = $roleModel->select();
        $assign['storage'] = $storageModel->select();
        $storageList = $staffStorageModel->getStaffStorage($userId);
        $storageList = empty($storageList) ? '' : implode(',', $storageList);
        $assign['storageUuid'] = $storageList;
        $this->assign($assign);
        return $this->fetch('edit');
    }

    public function getUser()
    {
        $result = $this->userService->getUserInfo();
        return json($result);
    }

    public function addUser()
    {
        $param = input();
        foreach ($param['storage'] as $k => $item) {
            $param['storage'][$k] = ['storage_uuid' => $item];
        }
        $this->userModel->addUser($param);
        $this->redirect('User/index');
    }

    public function editUser()
    {
        $param = input();
        $this->userModel->editUser($param);
        $this->redirect('User/index');
    }

    public function deleteUser()
    {
        $id = input('id');
        $this->userModel->deleteUser($id);
        $this->redirect('User/index');
    }

    public function checkUserName()
    {
        $id = input('id');
        $whereAnd = empty($id) ? '' : " and id != '$id'";
        $where = sprintf("binary user_login = '%s' $whereAnd", input('user_login'));
        $repeat = $this->userModel->where($where)->find();
        return json(boolval($repeat));
    }

}
